<template>
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-select
                class="m-2"
                placeholder="选择品牌"
                size="small"
                style="width: 100%"
                v-model="queryDto.brandId"
            >
              <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类">
            <el-cascader
                :props="categoryProps"
                style="width: 100%"
                v-model="searchCategoryIdList"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="search">
          搜索
        </el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <!--  添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="showDialog">添 加</el-button>
  </div>
  <!--  添加对话框-->
  <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
    <el-form label-width="120px">
      <el-form-item label="品牌">
        <el-select
            class="m-2"
            placeholder="选择品牌"
            size="small"
            v-model="categoryBrand.brandId"
        >
          <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类">
        <el-cascader
            :props="categoryProps"
            v-model="categoryBrand.categoryId"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  数据展示表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="categoryName" label="分类"/>
    <el-table-column prop="brandName" label="品牌"/>
    <el-table-column prop="logo" label="品牌图标" #default="scope">
      <img :src="scope.row.logo" width="50"/>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间"/>
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="delShow(scope.row.id)">
        删除
      </el-button>
    </el-table-column>
  </el-table>
<!--  删除对话框-->
  <el-dialog
      v-model="delDialogVisible"
      title="警告"
      width="500"
      :before-close="handleClose"
  >
    <span>确定要删除吗</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="delCategoryBrand">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  分页-->
  <el-pagination
      v-model:current-page="pageParams.page"
      v-model:page-size="pageParams.limit"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {findAll} from '@/api/brand'
import {getCategoryListByParentId} from "@/api/category"
import {getCategoryBrandByPageAndQueryDto, savaCategoryBrand, editCategoryBrand,deleteCategoryBrand} from "@/api/categoryBrand"
import {ElMessage} from "element-plus";
// import { FindAllProductUnit } from '@/api/productUnit.js'
// 控制删除对话框的显示
const delDialogVisible=ref(false);
//删除按钮
const delShow=(id)=>{
  console.log("要被删除的id"+id)
  //提示用户是否要真的删除
  delDialogVisible.value=true
  delId.value=id

}
//定义删除的响应式对象
const delId=ref({
   id:''
})
// 用户点击x子
const handleClose=()=>{
  ElMessage.info("未操作")
  delDialogVisible.value=false
}
//用户点击取消
const cancel=()=>{
  ElMessage.info("取消成功")
  delDialogVisible.value=false
}
//用户点击删除确定直接调用删除方法
const delCategoryBrand=async ()=> {
  const {code} = await deleteCategoryBrand(delId.value);
  if(code===200){
    ElMessage.success("删除成功")
    //关闭对话框
    delDialogVisible.value=false
    //刷新数据
    fetchData()
  }

}
// 提取修改品牌分类方法
const edit = async () => {

  //  分类没有回显需要判断是否满足要要求
  if (categoryBrand.value.categoryId.length != 3) {
    ElMessage.info("请填写分类")
    return
  }
  //品牌回显了,不可能为空不用判断了
  // categoryBrand.value.categoryId = categoryBrand.value.categoryId[2];
  // if (!categoryBrand.value.brandId) {
  //   ElMessage.info("请填写品牌")
  //   return
  // }
  const {code} = await editCategoryBrand(categoryBrand.value)
  //提示信息
  ElMessage.success("修改成功")
  //关闭对话框
  dialogVisible.value = false
  //刷新数据
  fetchData()
}
//修改回显
const editShow = (row) => {
  // console.log(row)
  //回显  这里只做的brand品牌回显,并没有做 category回显示
  categoryBrand.value = row
  //显示对话框
  dialogVisible.value = true
}

//提交按钮
const saveOrUpdate = () => {
  //判断是否有id,有id修改,没有id新增
  console.log(categoryBrand.value.id)
  if (categoryBrand.value.id) {

    edit()
  } else {
    add();
  }
}
// 抽取新增方法
const add = async () => {

  /**
   * console.log(categoryBrand.value)
   * 输出的是这个对象, categoryId我们只要第三级  categoryId[2]
   * {
   *     "id": "",
   *     "brandId": 1,
   *     "categoryId": [
   *         1,
   *         2,
   *         4
   *     ]
   * }
   */
  //  非空判断
  if (categoryBrand.value.categoryId.length != 3) {
    ElMessage.info("请填写分类")
    return
  }
  //拿到第三级的分类id
  categoryBrand.value.categoryId = categoryBrand.value.categoryId[2];
  if (!categoryBrand.value.brandId) {
    ElMessage.info("请填写品牌")
    return
  }
  console.log(categoryBrand.value)

  const {code,message} = await savaCategoryBrand(categoryBrand.value)
  if (code === 200) {
    ElMessage.success("添加成功")
    //关闭对话框
    dialogVisible.value = false
    //刷新
    fetchData()
  }else {
    ElMessage.error(message)
  }
}
//新增绑定的数据模型
// 如果是对象的话需要带id, 方便区分是新增还是更新
const defaultCategoryBrand = {
  id: "",
  brandId: "",
  categoryId: ""
}

const categoryBrand = ref(defaultCategoryBrand)

//控制显示对话框的变量
const dialogVisible = ref(false)
//点击添加按钮触发的事件
const showDialog = () => {
  // 清空数据模型,防止干扰
  categoryBrand.value.brandId = ''
  categoryBrand.value.categoryId = ''
  dialogVisible.value = true
}

// 重置按钮
const reset = () => {
  queryDto.value = {}
  searchCategoryIdList.value = []
  fetchData()
}
// 每页大小发生改变
const handleSizeChange = () => {
  fetchData()
}
//页数发生改变
const handleCurrentChange = () => {
  fetchData()
}
const searchCategoryIdList = ref([])
//搜索按钮
const search = () => {
  //说明选中了三级分类,这样才有效
  if (searchCategoryIdList.value.length == 3) {
    queryDto.value.categoryId = searchCategoryIdList.value[2]
  }
  console.log(queryDto.value.brandId)
  console.log(queryDto.value.categoryId)
  fetchData()
}
//  挂载加载 所有品牌的列表
onMounted(() => {
  //查询全部品牌
  getAllBrandList()
  //主数据取,查询品牌和分类的对应关系列表
  fetchData()
})
//封装查询品牌和分类的对应关系列表
const fetchData = async () => {
  const {data} = await getCategoryBrandByPageAndQueryDto(pageParams.value.page, pageParams.value.limit, queryDto.value);
  //拿到的是pageInfo对象, 有total和list属性
  list.value = data.list;
  total.value = data.total;
}

//封装查询条件
const queryDto = ref({
  brandId: "",
  categoryId: ""
})
//定义分页查询模型
const defaultPageParam = {
  page: 1,
  limit: 10
}
// 响应式对象
const pageParams = ref(defaultPageParam)
// 查询全部品牌
const getAllBrandList = async () => {
  const {data} = await findAll()
  brandList.value = data
}


// ================数据模型定义  start ===============================================
// 定义搜索表单数据模型, 显示品牌的分类
const brandList = ref([])

const props = {
  lazy: true,
  value: 'id',
  label: 'name',
  leaf: 'leaf',
  async lazyLoad(node, resolve) {   // 加载数据的方法
                                    // 没有id 说明是父级标签undefined
    if (typeof node.value === 'undefined') node.value = 0;
    // 查询后设置子标签
    const {data} = await getCategoryListByParentId(node.value);
    //遍历后新增一个leaf属性
    data.forEach(item => {
      //后端传过来的 hasChildren=true 表示有子节点
      // elementPlus 的leaf =true表示是叶子节点
      // 所以这里要加一个!
      item.leaf = !item.hasChildren
    })
    resolve(data)  // 返回数据
  }
};
const categoryProps = ref(props)

// 定义表格数据模型
const list = ref([])

// 分页条数据模型
const total = ref(0)

//======   数据模型定义end========================================================
</script>
<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>